package com.fxm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.dao.RecordMapper;
import com.fxm.domain.Record;
import com.fxm.enums.AnswerEnum;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.ErrorService;
import com.fxm.service.RecordService;
import com.fxm.vo.RankVO;
import com.fxm.vo.param.RecordParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 答题记录 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2021-01-07
 */
@Slf4j
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {

    @Autowired
    private ErrorService errorService;

    @Override
    public List<Record> listRecordOpenid() {
        return baseMapper.listRecordOpenid();
    }

    @Override
    public RespEntity insertRecordAnswer(RecordParam recordParam) {
        if (Objects.isNull(recordParam)) {
            log.info("参数为空");
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }

        //异步接入 错题记录
        errorService.errorDataAccess(recordParam);

        //数据组装
        Record record = dataPackage(recordParam);
        //添加答题记录
        baseMapper.insertRecord(record);
        log.info("同步用户答题记录成功，record={}", record);
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 数据组装
     * @param recordParam
     * @return
     */
    private Record dataPackage(RecordParam recordParam) {
        Record record = new Record();
        record.setOpenid(recordParam.getOpenid());
        record.setQuestionId(recordParam.getQuestionId());
        AnswerEnum answerEnum = AnswerEnum.getInstance(recordParam.getIsRight());
        if (Objects.nonNull(answerEnum)) {
            record.setIsRight(answerEnum.getDesc());
        }
        return record;
    }

    @Override
    public List<RankVO> todayAnswer(String begin, String end) {
        return baseMapper.todayAnswer(begin, end);
    }

    @Override
    public List<RankVO> maxHistoryAnswer() {
        return baseMapper.maxHistoryAnswer();
    }
}
